package com.gitee.wsl.net

import com.gitee.wsl.net.url.URLDecoder
import com.gitee.wsl.net.url.Url
import com.gitee.wsl.net.url.path


object UrlUtils {
    fun extractNameFromLink(link: String): String? {
        return runCatching {
            Url(link)
        }.map { url ->
            val foundName = url.path
                .split("/").lastOrNull { it.isNotBlank() }?.let {
                    kotlin.runCatching {
                        URLDecoder.decode(it)
                    }.getOrNull()
                }
            if (foundName != null) {
                return@map foundName
            }
            url.host.replace('.', '_')
        }
            .getOrNull()
    }

    /*fun openUrl(url: String) {
        kotlin.runCatching {
            val desktop = Desktop.getDesktop()
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                desktop.browse(URI(url))
            }
        }
    }*/

    data class Path(
        val pathString:String
    )

    data class TreeNode(val path: String, val pathObj: Path? = null, val children: MutableList<TreeNode> = mutableListOf()) {
        override fun toString(): String {
            return path.substringAfterLast('/')
        }
    }

    internal fun buildPathTree(paths: Map<String, Path>): TreeNode {
        val root = TreeNode("", null, mutableListOf()) // Root node with empty path

        val nodes = mutableMapOf<String, TreeNode>()
        nodes[""] = root

        for (path in paths.values.sortedBy { it.pathString }) {
            var currentPathString = path.pathString
            val pathParts = mutableListOf<String>()

            while (currentPathString.isNotEmpty() && !nodes.containsKey(currentPathString)) {
                pathParts.add(currentPathString)
                val lastSlashIndex = currentPathString.lastIndexOf('/')
                if (lastSlashIndex != -1) {
                    currentPathString = currentPathString.substring(0, lastSlashIndex)
                } else {
                    currentPathString = "" // Reached root
                }
            }

            pathParts.reversed().forEach { part ->
                nodes.getOrPut(part) { TreeNode(part, pathObj = paths[part]) }
                val lastSlashIndex = part.lastIndexOf('/')
                val parentPathString = if (lastSlashIndex != -1) part.substring(0, lastSlashIndex) else ""
                val parentNode = nodes[parentPathString]!!
                val currentNode = nodes[part]!!
                parentNode.children.add(currentNode)
            }
        }

        return root
    }

}